const express = require('express');
const bodyParser = require('body-parser');
const {ipcMain} = require('electron');
const {getGlobalStat} = require('../renderer/aria2/aria2');
const fs = require('fs');
function startHttpServer(mainWindow) {
	const app = express();
	const port = 16600; // 自定义端口号，可以根据需要修改
	
	// 允许跨域请求
	app.use((req, res, next) => {
		res.setHeader('Access-Control-Allow-Origin', '*');
		res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
		res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
		next();
	});
	app.use(bodyParser.json());
	
	// 处理 POST 请求的 /api/send-json 路径
	app.post('/api/downloadDataSend', (req, res) => {
		const jsonData = req.body;
		console.log('Received JSON data via HTTP POST:', jsonData);
		if (jsonData) {
			// 发送数据回渲染进程（如果需要）
			mainWindow.webContents.send('download-data-send', jsonData);
		}
		// 发送响应给客户端
		res.send({
			code: 200,
			data: jsonData
		});
	});
	
	app.post('/api/getGlobalStat', (req, res) => {
		const jsonData = req.body;
		console.log('Received JSON data via HTTP POST---:', jsonData);
		getGlobalStat().then((response) => {
			console.log("response.data.result", response.data)
			res.send({
				code: 200,
				data: response
			});
		})
		// 发送响应给客户端
		
	});
	
	
	// 启动 HTTP 服务
	app.listen(port, () => {
		console.log(`HTTP server is running on http://localhost:${port}`);
		console.log(`Server is listening on port ${port}`);
		console.log(`Express PID: ${process.pid}`);
		
		// Save the PID to a file or send it back to the main process
		fs.writeFileSync('express.pid', process.pid.toString());
	});
	
	// 处理从渲染进程发送的 JSON 数据请求
	ipcMain.on('send-json-from-renderer', (event, jsonData) => {
		// 在这里处理接收到的 JSON 数据，可以进行进一步处理或发送给其他渲染进程等
		console.log('Received JSON data from renderer process:', jsonData);
		// 发送数据回渲染进程（如果需要）
		mainWindow.webContents.send('download-data-send', jsonData);
	});
	
	return app
}

module.exports = {
	startHttpServer
};
